import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { useRequest } from 'ahooks'
import { message, Table, Button,notification } from 'antd';
import _ from 'lodash';
import { NavLink } from 'umi';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons'
import type { NotificationPlacement } from 'antd/es/notification/interface';

// 发起网络请求，审核新闻要根据不同角色显示不同信息。显示的auditState!=0(_ne=0)【审核中1，已通过2，未通过3】,
// 超级管理员的审核新闻要显示所有人的，auditState=1（属于审核中）的新闻信息
// 区域管理员的审核新闻，只能显示同区域下的所有编辑者(包括自己)，以及auditState=1（属于审核中）的新闻信息
const getCurrentAuditListRequest = () => {
    return axios.get(`http://localhost:3000/news?_expand=category&auditState=1`)
};


// 发起网络请求，通过更新新闻信息
const updateNewsRequest = (item: any, id: string | number | undefined,textType:number) => {
    return axios.patch(`http://localhost:3000/news/${id}`, {
        ...item
    })
}
type stringKey = Record<string, string>;
export default function Audit() {
    const [currentRoleAuditList, setCurrentRoleAuditList] = useState<any>([]);
    //从localStorage获取当前用户信息
    const currentUser = JSON.parse(localStorage.getItem('token') as string);
    // useRequest - 获取auditState=1新闻信息
    const { run: getCurrentAuditListData, loading: getCurrentNewsLoading } = useRequest(getCurrentAuditListRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            if (result.status === 200) {
                const roleObj: stringKey = {
                    '1': 'SuperAdmin',
                    '2': 'Admin',
                    '3': 'Editor'
                }
                if (currentUser?.length > 0) {
                    // 超级管理员的审核新闻要显示所有人的新闻信息
                    if (roleObj[currentUser[0].roleId] === 'SuperAdmin') {
                        setCurrentRoleAuditList(result.data);
                        console.log(`${roleObj[currentUser[0].roleId]}`, result.data);
                    }
                    // 区域管理员的审核新闻，只能显示同区域下的所有编辑者新闻信息
                    else {
                        let newsList: Array<any> = _.cloneDeep(result.data);
                        // 先筛选出同区域的，再筛选出编辑者以及自己
                        newsList = newsList.filter(item => item.region === currentUser[0].region)
                            .filter(item => item.author === currentUser[0].username || roleObj[item.roleId] === 'Editor');
                        setCurrentRoleAuditList(newsList);
                        console.log(`${roleObj[currentUser[0].roleId]}`, newsList);
                    }
                }

            }
        },
        onError(e, params) {
            message.warning('请求新闻数据失败')
        },
    });
    const publishStateObj: stringKey = {
        '0': '草稿箱',
        '1': '审核列表',
        '2': '【发布管理-已发布页面】',
        '3': '待发布'
    };
    // useRequest - 更新当前id新闻信息
    const { run: UpdateCurrentNewsData, loading: updateLoading } = useRequest(updateNewsRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            if (result.status === 200) {
                // 更新审核列表信息
                getCurrentAuditListData();
                console.log(result.data);
                openNotification('bottomRight', params[2]);
            }
        },
        onError(e, params) {
            message.warning('请求新闻数据失败')
        },
    })
    const handelAuditNews = (type: number, item: any) => {
        let newItem = _.cloneDeep(item);
        switch (type) {
            // 审核不通过，将auditState改为3，待审核=》未通过，publishState为0，表示未发布
            case 0:
                newItem.auditState = 3;
                newItem.publishState = 0;
                UpdateCurrentNewsData(newItem, newItem.id,1);
                break;
                // 审核通过，将auditState改为2，已通过，publishState为1，表示待发布；待审核=》已通过；未发布=》待发布
            case 1:
                newItem.auditState = 2;
                newItem.publishState = 1;
                UpdateCurrentNewsData(newItem, newItem.id,1)
                break;
            default:
                break;
        }

    };
    //#region 消息通知框
    const openNotification = (placement: NotificationPlacement, auditState: number) => {
        notification.open({
            message: `通知`,
            description: `你可以到${publishStateObj[auditState]}中查看您的新闻的审核状态`,
            placement,
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    };
    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            key: 'title',
            render: (title: string, item: any) => {
                return <NavLink to={`/news-manage/preview/${item.id}`}>{title}</NavLink>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
            key: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            key: 'category',
            render: (category: any) => category.title
        },

        {
            title: '操作',
            render: (item: any) => {
                return (<div>
                    <Button type='primary' shape="circle" style={{ 'marginRight': '10px' }} icon={<CheckOutlined />} onClick={() => {
                        handelAuditNews(1, item)
                    }}></Button>
                    <Button danger shape="circle" style={{ 'marginRight': '10px' }} icon={<CloseOutlined />} onClick={() => {
                        handelAuditNews(0, item)
                    }}></Button>
                </div>)
            }
        }
    ];
    useEffect(() => {
        getCurrentAuditListData();
    }, [currentUser[0].roleId, currentUser[0].username, currentUser[0].region])
    return (
        <div>
            <Table dataSource={currentRoleAuditList} columns={columns} loading={getCurrentNewsLoading} 
            rowKey={(item) => item.id} sticky scroll={{ y: '63vh' }} />
        </div>
    )
}
